#!/usr/bin/env python3
# coding: utf-8

import sys, os, time, random


if __name__ == "__main__":
    tests_ct = int(sys.argv[1])
    text_len = int(sys.argv[2])
    N = int(sys.argv[3]) if len(sys.argv) == 4 else random.randint(1, 10 ** 5)

    assert os.system('gcc -g3 -Wall 2013-04-29-a.c') == 0, 'compile failed'
    assert os.access('a.out', os.X_OK|os.R_OK) == True, 'no executable'

    for i in range(tests_ct):
        text = ''
        for j in range(text_len):
            text += chr(random.randint(ord('a'), ord('z')))
        in_data = '{}\n{}\n'.format(text, N)
        tests_char_ct = 0
        assert os.access('answer.txt', os.R_OK) == False
        ans_file = open('answer.txt', 'w')
        for j in range(N):
            if random.randint(0, 2) == 0:
                lo = random.randint(0, len(text) - 2)
                hi = random.randint(lo + 1, len(text) - 1)
                substr = text[lo:hi]
            else:
                test_len = random.randint(1, max((10 ** 6 - tests_char_ct) // 2, 10))
                substr = ''.join([chr(random.randint(ord('a'), ord('z'))) for i in range(min(test_len, len(text) + 2))])

            if substr in text:
                ans_file.write(substr + '\n')

            tests_char_ct += len(substr)
            in_data += substr + '\n'
        assert os.access('input.txt', os.R_OK) == False
        assert os.access('output.txt', os.R_OK) == False
        f = open('input.txt', 'w')
        f.write(in_data)
        f.flush()
        f.close()
        ans_file.flush()
        ans_file.close()

        start_time = time.time()
        #os.spawnl(os.P_WAIT, '/bin/sh', ['-c', './a.out', '<input.txt', '>output.txt'])
        os.system('./a.out <input.txt >output.txt')
        end_time = time.time()
        print('{0}: test #{1} executed in {2}'.format(sys.argv[0], i, end_time - start_time))

        # check
        ans_file = open('answer.txt', 'r')
        f = open('output.txt', 'r')
        answer = [x.strip() for x in ans_file.readlines()]
        output = [x.strip() for x in f.readlines()]

        if answer != output:
            print('{0}: test #{1} FAILED'.format(sys.argv[0], i),
                  'expected = {0}'.format(answer),
                  'got      = {0}'.format(output), sep='\n')
            break
        else:
            print('{0}: test #{1} OK'.format(sys.argv[0], i))
            os.unlink('input.txt')
            os.unlink('output.txt')
            os.unlink('answer.txt')
